package com.example.programming.sys.controller;

import com.alibaba.fastjson.JSONObject;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.programming.common.Result;
import com.example.programming.common.tools.*;
import com.example.programming.sys.entity.UcenterMember;
import com.example.programming.sys.entity.User;
import com.example.programming.sys.entity.vo.RegisterVo;
import com.example.programming.sys.entity.vo.UserVo;
import com.example.programming.sys.mapper.UcenterMemberMapper;
import com.example.programming.sys.mapper.UserMapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 会员表 前端控制器 chrimer
 * </p>
 *
 * @author chrimer
 * @since 2020-09-02
 */
@RestController
@Api(description = "登入注册")
@RequestMapping("/sys/member")
@CrossOrigin
public class UcenterMemberController extends BaseController {
    @Autowired
    private UcenterMemberMapper ucenterMemberMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @PostMapping("/Loginbymsm")
    public Result Loginbymsm(@RequestBody RegisterVo registerVo) {
        Result result = new Result();
        String mobile = registerVo.getMobile();
        String code = registerVo.getCode();
        if (StringUtils.isEmpty(mobile) || StringUtils.isEmpty(code)) {
            result.fail("有值为空，登入失败");
            return result;
        }

        String mobleCode = redisTemplate.opsForValue().get(mobile);
        System.out.println(mobile);
        System.out.println(mobleCode);
        if (!code.equals(mobleCode)) {
            result.fail("验证码错误，登入失败");
            return result;
        }

        UcenterMember member = ucenterMemberMapper.selectOne(new QueryWrapper<UcenterMember>().eq("mobile", mobile));
        if(null == member) {
            result.fail("没有这个用户");
            return result;
        }

        if(member.getIsDisabled()) {
            result.fail("账号被禁用");
            return result;
        }

        String token = JwtUtil.generateToken(member.getId());
        result.setToken(token);
        result.setData(member);
        return result;
    }
    

    @PostMapping("/bindLogin")
    public Result bindLogin(@RequestBody UcenterMember memberVo) {
        Result result = new Result();
        String nickname = memberVo.getNickname();
        String password = memberVo.getPassword();

        //校验参数
        if(StringUtils.isEmpty(nickname) ||
                StringUtils.isEmpty(password)) {
            result.fail("值有空");
            return result;
        }

        //获取会员
        UcenterMember member = ucenterMemberMapper.selectOne(new QueryWrapper<UcenterMember>().eq("nickname", nickname));
        if(null == member) {
            result.fail("没有这个用户");
            return result;
        }

//        校验密码
        if(!MD5.encrypt(password).equals(member.getPassword())) {
            result.fail("密码错误");
            return result;
        }

        //校验是否被禁用
        if(member.getIsDisabled()) {
            result.fail("账号被禁用");
            return result;
        }

        //使用JWT生成token字符串
//        String token = JwtUtils.getJwtToken(member.getId(), member.getNickname());
//        result.setData("token", token);
        String token = JwtUtil.generateToken(member.getId());
        result.setToken(token);
        return result;
    }

    @ApiOperation(value = "会员注册")
    @PostMapping("register")
    public Result register(@RequestBody RegisterVo registerVo) {
        Result result = new Result();

        //获取注册信息，进行校验
        String nickname = registerVo.getNickname();
        String mobile = registerVo.getMobile();
        String password = registerVo.getPassword();
        String code = registerVo.getCode();

        //校验参数
        if (StringUtils.isEmpty(mobile) ||
                StringUtils.isEmpty(mobile) ||
                StringUtils.isEmpty(password) ||
                StringUtils.isEmpty(code)) {
            result.fail("有值为空，注册失败");
            return result;
        }

        //校验校验验证码
        //从redis获取发送的验证码
        String mobleCode = (String) redisTemplate.opsForValue().get(mobile);
        System.out.println(mobleCode);
        if (!code.equals(mobleCode)) {
            result.fail("验证码错误，注册失败");
            return result;
        }

        //查询数据库中是否存在相同的手机号码
        Integer count = ucenterMemberMapper.selectCount(new QueryWrapper<UcenterMember>().eq("mobile", mobile));
        if (count.intValue() > 0) {
            result.fail("已有手机号注册失败");
            return result;
        }

        //添加注册信息到数据库
        UcenterMember member = new UcenterMember();
        member.setNickname(nickname);
        member.setMobile(registerVo.getMobile());
        member.setPassword(MD5.encrypt(password));
        member.setIsDisabled(false);
        member.setAvatar("http://thirdwx.qlogo.cn/mmopen/vi_32/DYAIOgq83eoj0hHXhgJNOTSOFsS4uZs8x1ConecaVOB8eIl115xmJZcT4oCicvia7wMEufibKtTLqiaJeanU2Lpg3w/132");
//        this.save(member);
        ucenterMemberMapper.insert(member);
        User user = new User();
        System.out.println("nickname:"+nickname);
        user.setNickname(nickname);
        System.out.println("user:"+user);
        userMapper.insert(user);
        result.success("注册成功");
        return result;
    }

    @GetMapping(value = "/send/{phone}")
    public Result code(@PathVariable("phone") String phone) {
        Result result = new Result();
        String code = redisTemplate.opsForValue().get(phone);
        System.out.println(phone);
        if (!StringUtils.isEmpty(code)) {
            result.success("验证码存在,无须失败");
            System.out.println(code);
            return result;
        }
        code = RandomUtil.getFourBitRandom();
        Map<String, Object> param = new HashMap<>();
        param.put("code", code);
        if (StringUtils.isEmpty(phone)) {
            result.fail("发送失败");
            return result;
        }

        DefaultProfile profile =
                DefaultProfile.getProfile("default", "LTAI4GEj4aBvnfG3EZU71UwK", "O0FFTyzQelUX7gVK3k5nxEpceZxmNE");
        IAcsClient client = new DefaultAcsClient(profile);

        CommonRequest request = new CommonRequest();
        //request.setProtocol(ProtocolType.HTTPS);
        request.setMethod(MethodType.POST);
        request.setDomain("dysmsapi.aliyuncs.com");
        request.setVersion("2017-05-25");
        request.setAction("SendSms");

        request.putQueryParameter("PhoneNumbers", phone);
        request.putQueryParameter("SignName", "宇课堂在线教育平台");
        request.putQueryParameter("TemplateCode", "SMS_200701778");
        request.putQueryParameter("TemplateParam", JSONObject.toJSONString(param));

        try {
            CommonResponse response = client.getCommonResponse(request);
            System.out.println(response.getData());
            if (response.getHttpResponse().isSuccess()) {
                redisTemplate.opsForValue().set(phone, code, 50, TimeUnit.MINUTES);
                result.success("发送成功");
                return result;
            }
        } catch (ServerException e) {
            e.printStackTrace();
        } catch (ClientException e) {
            e.printStackTrace();
        }
        result.success("发送成功");
//        result.setStatusCode("200");
        return result;
    }

    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNum", paramType = "query", value = "当前页码", required = true),
            @ApiImplicitParam(name = "pageSize", paramType = "query", value = "每页显示记录数", required = true)
    })
    @ApiOperation(value = "分页获取UcenterMember信息")
    @RequestMapping(method = RequestMethod.POST, value = "/page")
    public Result page(
            Integer pageNum,
            Integer pageSize) {
        Result result = new Result();
        Page<UcenterMember> page = new Page<UcenterMember>(pageNum, pageSize);
        UcenterMember parms = new UcenterMember();
        QueryWrapper<UcenterMember> warpper = new QueryWrapper<UcenterMember>(parms);

        result.setData(ucenterMemberMapper.selectPage(page, warpper));
        return result;
    }

    @ApiOperation(value = "保存修改UcenterMember信息")
    @RequestMapping(method = RequestMethod.POST, value = "/save")
    public Result save(@RequestBody UcenterMember entity) {
        Result result = new Result();
        if (entity.getId() == null) {
            ucenterMemberMapper.insert(entity);
        } else {
            ucenterMemberMapper.updateById(entity);
        }
        return result;
    }

    @ApiOperation(value = "按id删除UcenterMember，可以传入多个id用，隔开")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "ids", paramType = "query", value = "传入的id串，用，隔开", required = true)
    })
    @RequestMapping(method = RequestMethod.DELETE, value = "/delete")
    public Result delete(String ids) {
        Result result = new Result();
        List<String> deleteIds = new ArrayList<String>();
        for (String id : ids.split(",")) {
            deleteIds.add(id);
        }
        ucenterMemberMapper.deleteBatchIds(deleteIds);
        return result;
    }
    @PostMapping("/checkPassword")
    public Result checkPassword(@RequestBody UserVo userVO) {
        String username = userVO.getUserName();
        String password = userVO.getPassWord();
        System.out.println(username+" "+password);
        Result result = new Result();
        //校验参数
        if(StringUtils.isEmpty(password)) {
            result.fail("密码为空");
            return result;
        }
        //获取会员
        UcenterMember member = ucenterMemberMapper.selectOne(new QueryWrapper<UcenterMember>().eq("nickname", username));
        if(null == member) {
            result.fail("没有这个用户");
            return result;
        }

        //        校验密码
        if(!MD5.encrypt(password).equals(member.getPassword())) {
            result.fail("密码错误");
            return result;
        }
        //校验是否被禁用
        //        if(member.getIsDisabled()) {
        //            result.fail("账号被禁用");
        //            return result;
        //        }

        //使用JWT生成token字符串
        //        String token = JwtUtils.getJwtToken(member.getId(), member.getNickname());
        //        result.setData("token", token);
        //        String token = JwtUtil.generateToken(member.getId());
        //        result.setToken(token);
        return result;
    }
    @RequestMapping(method = RequestMethod.GET,value = "/getAvatar")
    public Result getAvatar(String name){
        Result result = new Result();
        result.setData(ucenterMemberMapper.getavatar(name));
        System.out.println("avatar:"+ucenterMemberMapper.getavatar(name));
        return  result;
    }


    @RequestMapping(method= RequestMethod.POST,value="/upload")
    public FileResult upload(MultipartFile file, String username) throws IOException {
        String originalFileName = file.getOriginalFilename();
        System.out.println("test");
        OSS ossClient = new OSSClientBuilder().build(
                AliyunOSSConfigConstant.END_POINT,
                AliyunOSSConfigConstant.ACCESSKEY_ID,
                AliyunOSSConfigConstant.ACCESSKEY_SECRET
        );
        InputStream inputStream = file.getInputStream();
        ossClient.putObject(AliyunOSSConfigConstant.BUCKET_NAME,originalFileName,inputStream);

        ossClient.shutdown();

        String url = "https://"+AliyunOSSConfigConstant.BUCKET_NAME+"."+AliyunOSSConfigConstant.END_POINT+"/"+originalFileName;
        System.out.println("username:"+username);
        System.out.println("url:"+url);
        ucenterMemberMapper.updateAvatar(username,url);
        return new FileResult(true,originalFileName,url);

    }


}
